package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.convention.exception.ServiceException;
import com.nageoffer.shortlink.admin.dao.entity.GroupDO;
import com.nageoffer.shortlink.admin.dao.mapper.GroupMapper;
import com.nageoffer.shortlink.admin.dto.req.GroupSaveRequestDTO;
import com.nageoffer.shortlink.admin.dto.req.GroupSortUpdateRequestDTO;
import com.nageoffer.shortlink.admin.dto.resp.GroupListRespDTO;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 刘新智
 * @Date: 2025/10/20 19:08
 * @Description:
 * @Version: v1.0
 */
@Service
@Slf4j
@AllArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {


    private final UserService userService;

    @Override
    public void save(GroupSaveRequestDTO groupSaveRequestDTO) {
        String groupName = groupSaveRequestDTO.getGroupName();
        String username = userService.getCurrentUserInfo().getUsername();
        String gId;
        GroupDO oldGroupDO;
        
        // 通过循环确保生成的gid是唯一的
        do {
            gId = String.valueOf(IdUtil.getSnowflakeNextId());
            oldGroupDO = this.getOne(Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getGid, gId)
                    .eq(GroupDO::getUsername, username));
        } while (oldGroupDO != null);
        
        // 新增分组
        GroupDO groupDO = new GroupDO();
        groupDO.setGid(gId);
        groupDO.setName(groupName);
        groupDO.setSortOrder(0);
        groupDO.setUsername(username);
        boolean save = this.save(groupDO);
        if(!save){
            throw new ServiceException("分组保存失败");
        }
        log.info("新增短链接分组：{}", groupDO);
    }

    @Override
    public List<GroupListRespDTO> groupList() {
        List<GroupDO> groupDOList = this.list(Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, userService.getCurrentUserInfo().getUsername())
                .eq(GroupDO::getDelFlag, 0)
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime));
        log.info("查询短链接分组列表：{}", groupDOList);
        return BeanUtil.copyToList(groupDOList, GroupListRespDTO.class);
    }

    @Override
    public void delete(String gid) {
        // 1. 参数校验
        if(gid == null){
            throw new ServiceException("短链接分组gid不能为空");
        }
        // 2. 查询出需要删除的分组
        GroupDO groupDO = baseMapper.selectOne(Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, userService.getCurrentUserInfo().getUsername())
                .eq(GroupDO::getDelFlag, 0));
        if(groupDO == null){
            throw new ServiceException("短链接分组不存在");
        }
        // 3. 删除分组
        int delete = baseMapper.delete(Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, userService.getCurrentUserInfo().getUsername())
                .eq(GroupDO::getDelFlag, 0));
        if(delete <= 0){
            throw new ServiceException("短链接分组删除失败");
        }
        log.info("删除短链接分组：{}", groupDO);
    }

    @Override
    public void updateSort(List<GroupSortUpdateRequestDTO> groupSortUpdateRequestDTOList) {
        for (GroupSortUpdateRequestDTO groupSortUpdateRequestDTO : groupSortUpdateRequestDTOList) {
            String gid = groupSortUpdateRequestDTO.getGid();
            Integer sortOrder = groupSortUpdateRequestDTO.getSortOrder();
            GroupDO groupDO = baseMapper.selectOne(Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, userService.getCurrentUserInfo().getUsername())
                    .eq(GroupDO::getGid, gid)
                    .eq(GroupDO::getDelFlag, 0));
            if(groupDO == null){
                log.error("短链接分组不存在：{}", gid);
                continue;
            }
            groupDO.setSortOrder(sortOrder);
            int count = baseMapper.updateById(groupDO);
            if(count<=0){
                throw new ServiceException("分组排序更新失败");
            }
            log.info("更新短链接分组排序：{}", groupDO);
        }
    }
}